from django.db import models
from django.core.validators import ValidationError 
from django.contrib.admin.models import User
from django.template.defaultfilters import slugify
from vcore.main.templatetags.ago import ago

# Create your models here.

class SuspendManager(models.Manager):
    def get_query_set(self):
        return super(SuspendManager, self).get_query_set().filter(suspended = False)
        
class News(models.Model):
    title = models.CharField(maxlength = 250, )
    content = models.TextField()
    posted_by = models.ForeignKey(User, related_name = 'News posted by')
    post_date = models.DateTimeField(auto_now_add = True)
    suspended = models.BooleanField(default = False)
    objects = models.Manager()
    effective = SuspendManager()
    
    def __str__(self):
        return self.title
    
    def _get_ago(self):
        return ago(self.post_date)
    _get_ago.short_description = '''post date'''
    
    class Meta:
        verbose_name_plural = 'news items'
    
    class Admin:
        list_display = ('_get_ago', 'title', 'posted_by', 'suspended', )
        ordering = ('-post_date', )
        list_filter = ('suspended', 'posted_by', )

class Slug(models.Model):
    name = models.CharField(maxlength = 255, )
    type = models.CharField(maxlength = 8, radio_admin = True,
        choices = (('category', 'category'), ('tag', 'tag'), ))
    name_type = models.SlugField()
    #name_type = models.CharField(maxlength = 255, unique = True, editable = False)
    
    def __str__(self):
        return self.name
    
    def save(self):
        self.name_type = slugify(self.name + ' ' + self.type )
        super(Slug, self).save()
    
    class Admin:
        list_display = ('name', 'type', 'name_type', )
    
def is_category_same_name(field_data, all_data):
    field_data = field_data.lower()
    if Category.objects.filter(name = field_data).count() > 0:
        raise ValidationError, 'when "%s" category is trying to create.'%(field_data.upper())

class Category(models.Model):
    name = models.CharField(maxlength = 100, unique = True, 
        validator_list = [is_category_same_name],)
    suspended = models.BooleanField(default = False)
    slug = models.ForeignKey(Slug, editable = False)
    objects = models.Manager()
    effective = SuspendManager()

    def save(self):
        self.name = self.name.lower()
        if not self.id:
            slug = Slug()
            slug.name = self.name
            slug.type = 'category'
            slug.save()
            self.slug = slug
        else:
            slug = self.slug
            slug.name = self.name
            slug.save()
        super(Category, self).save()
    
    def _get_number_of_videos(self):
        return self.video_set.count()
    number_of_videos = property(_get_number_of_videos)
    
    def _get_view_videos(self):
        return '''<a href=/admin/main/video/?categories__id__exact=%d>video</a>'''%self.id
    _get_view_videos.allow_tags = True
    _get_view_videos.short_description = '''view_videos'''
    
    def __str__(self):
        return self.name
    
    class Meta:
        verbose_name_plural = 'categories'

    class Admin:
        list_display = ('name', 'number_of_videos', 'suspended', 
            '_get_view_videos', 'slug', )
        ordering = ('name', )
        list_filter = ('suspended', )

def is_tag_same_name(field_data, all_data):
    field_data = field_data.lower()
    if Tag.objects.filter(name = field_data).count() > 0:
        raise ValidationError, 'when "%s" tag is trying to create.'%(field_data.upper())

class Tag(models.Model):
    name = models.CharField(maxlength = 100, unique = True, 
        validator_list = [is_tag_same_name, ])
    suspended = models.BooleanField(default = False)
    slug = models.ForeignKey(Slug, editable = False)
    objects = models.Manager()
    effective = SuspendManager()

    def _get_number_of_videos(self):
        return self.video_set.count()
    number_of_videos = property(_get_number_of_videos)
    
    def _get_view_videos(self):
        return '''<a href=/admin/main/video/?tags__id__exact=%d>video</a>'''%self.id
    _get_view_videos.allow_tags = True
    _get_view_videos.short_description = '''view_videos'''

    view_videos = property(_get_view_videos)
    
    def validate(self):
        errors = super(Tag, self).validate()
        print 'fdsa', errors
        return errors
    
    
    def save(self):
        self.name = self.name.lower()
        if not self.id:
            slug = Slug()
            slug.name = self.name
            slug.type = 'tag'
            slug.save()
            self.slug = slug
        else:
            slug = self.slug
            slug.name = self.name
            slug.save()
        super(Tag, self).save()
    
    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'tags'

    class Admin:
        list_display = ('name', 'number_of_videos', 'suspended', 
            '_get_view_videos', 'slug', )
        ordering = ('name', )
        list_filter = ('suspended', )

class Video(models.Model):
    title = models.CharField(maxlength = 250, )
    embed_link = models.URLField(verify_exists = False, )
    upload_date = models.DateTimeField(auto_now_add = True)
    categories = models.ManyToManyField(Category, null = True, blank = True)
    tags = models.ManyToManyField(Tag, null = True, blank = True)
    description = models.TextField(null = True, blank = True)
    featured = models.BooleanField(default = False)
    suspended = models.BooleanField(default = False)
    objects = models.Manager()
    effective = SuspendManager()
    
    def _get_categories(self):
        return ','.join([value['name'] for value in self.categories.values()])
    _get_categories.short_description = '''categories'''  
    
    def _get_ago(self):
        return ago(self.upload_date)
    _get_ago.short_description = '''upload date'''
    
    def __str__(self):
        return self.title

    class Meta:
        verbose_name_plural = 'videos'

    class Admin:
        list_display = ('title', '_get_categories', '_get_ago', 'featured', 
            'suspended',  )
        ordering = ('-upload_date', )
        list_filter = ('featured', 'suspended', 'categories', 'tags', )

class Submitted_Video(models.Model):
    uploader_name = models.CharField(maxlength = 100, )
    title = models.CharField(maxlength = 250, )
    tags = models.CharField(maxlength = 100, null = True, blank = True)
    description = models.TextField(null = True, blank = True)
    submitted_date = models.DateTimeField(auto_now_add = True)
    video_link = models.URLField(verify_exists = False, )
    client_ip_address = models.CharField(maxlength = 15, null = True, blank = True, editable = False, )
    status = models.CharField(maxlength = 15, default = 'processing', radio_admin = True,
        choices = (('processing', 'processing'), ('accepted', 'accepted'), ('rejected', 'rejected')))

    def save(self):
        if self.status == 'accepted':
            self.accept()
        elif self.status == 'rejected':
            self.reject()
        super(Submitted_Video, self).save()
    
    def _get_ago(self):
        return ago(self.submitted_date)
    _get_ago.short_description = '''submitted date'''
    
    def accept(self):
        import re
        strTag = self.tags.strip()
        list_save_Tag = []
        if strTag != '':
            listTag = re.findall(r'\S+', strTag)
            for strTag in listTag:
                tag = Tag.objects.filter(name = strTag)
                if not tag:
                    tag = Tag()
                    tag.name = strTag
                    tag.suspended = False
                    tag.featured = False
                    tag.save()
                    list_save_Tag += [tag]
                else:
                    list_save_Tag += [tag[0]]
        
        video = Video.objects.filter(title = self.title)
        if not video:
            video = Video()
            video.title = self.title
            video.description = self.description
            video.embed_link = self.video_link
            video.save()
            for tag in list_save_Tag:
                video.tags.add(tag)
        else:
            video = video[0]
            list_old_tag = [value['id'] for value in video.tags.values('id')]
            for tag in list_save_Tag:
                print tag.id
                print list_old_tag
                if not (tag.id in list_old_tag):
                    video.tags.add(tag)
        video.save()
    
    def __str__(self):
        return self.uploader_name
    
    class Meta:
        verbose_name_plural = 'submitted videos'
    
    class Admin:
        list_display = ('_get_ago', 'uploader_name', 'title', 'status', 
            'client_ip_address', )
        ordering = ('-submitted_date', )
        list_filter = ('status', )
    
class Submitted_Feedback(models.Model):
    name = models.CharField(maxlength = 100, )
    email = models.EmailField()
    content = models.TextField()
    submitted_date = models.DateTimeField(auto_now_add = True)
    client_ip_address = models.CharField(maxlength = 15, null = True, blank = True, editable = False, )
    
    def _get_ago(self):
        return ago(self.submitted_date)
    _get_ago.short_description = '''submitted date'''
    
    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'submitted feedbacks'

    class Admin:
        list_display = ('_get_ago', 'name', 'email', 'client_ip_address', )
        ordering = ('-submitted_date', )

